home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 2536 < prev    next >
Encoding:
Internet Message Format  |  1996-08-06  |  2.0 KB

  1. Path: news.th-darmstadt.de!news
  2. From: Enno Sandner <enno@intellektik.informatik.th-darmstadt.de>
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: Function overloading problem
  5. Date: Thu, 18 Jan 1996 08:57:32 +0100
  6. Organization: Fachbereich Informatik, TH Darmstadt
  7. Message-ID: <30FDFD6C.167EB0E7@intellektik.informatik.th-darmstadt.de>
  8. References: <DLBxoH.GLw@ariel.cs.yorku.ca>
  9. NNTP-Posting-Host: kitz.intellektik.informatik.th-darmstadt.de
  10. Mime-Version: 1.0
  11. Content-Type: text/plain; charset=us-ascii
  12. Content-Transfer-Encoding: 7bit
  13. X-Mailer: Mozilla 2.0b5 (X11; I; SunOS 4.1.3 sun4m)
  14.  
  15. IAN J COLOMBY wrote:
  16. > I have the following code which in which the function call of f() inside
  17. > function g() doesn't behave the way I expected it to.
  18. > class B;
  19. > class C;
  20. > class A
  21. > {
  22. >    virtual void f(B*);
  23. >    virtual void f(C*);
  24. > };
  25. > class B: public A
  26. > {
  27. >    void f(B*);
  28. >    void f(C*);
  29. > };
  30. > class C: public A
  31. > {
  32. >    void f(B*);
  33. >    void f(C*);
  34. > };
  35. > void g(A* a1, A* a2)
  36. > {
  37. >         a1->f(a2);
  38. > }
  39. > The above code first of all won't compile unless I insert the following
  40. > line of code into each class definition:
  41. >         vitrual void f(A*) in class A or void f(A*) in classes B & C.
  42.  
  43. What else do you expect ?
  44. A pointer to a derived class may be silently converted to a base-class
  45. pointer but not vice versa.
  46.  
  47. > The next problem is that the above line f(A*) is the function that always
  48. > gets called in the class of a1 no matter what a2 is in function g().  a1
  49. > and a2 will never be of class A, they will only be of either class B or
  50. > class C, so I'm not sure why the the call a1->f(a2) always calls the
  51. > function f(A*) in the class of a1, and not f(B*) or f(C*) depending on
  52. > what class a2 is.
  53. > Any help in solving this problem would be appreciated.
  54.  
  55. The appropriate function is determined at compile-time, ie. the static-type
  56. is used to choose the function, which is in this case A.
  57. A reasonable solution to this problem seems to be the 'Visitor' pattern as
  58. described in the 'Design Patterns' book.
  59.  
  60.     Enno
  61.